package com.lyl.serviceedu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyl.commonutils.R;
import com.lyl.exception.ZxjyException;
import com.lyl.serviceedu.entity.Course;
import com.lyl.serviceedu.entity.Subject;
import com.lyl.serviceedu.entity.excel.ExcelSubjectData;
import com.lyl.serviceedu.entity.vo.CourseApiVo;
import com.lyl.serviceedu.listener.SubjectExcelListener;
import com.lyl.serviceedu.mapper.SubjectMapper;
import com.lyl.serviceedu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author 雷艳玲
 * @since 2022-06-08
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {
    @Autowired
    SubjectMapper subjectMapper;


    //添加课程分类
//poi读取excel内容
    @Override
    public void batchImport(MultipartFile file) {
        try {
            //1 获取文件输入流
            InputStream inputStream = file.getInputStream();

            // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
            EasyExcel.read(inputStream, ExcelSubjectData.class, new SubjectExcelListener(this)).sheet().doRead();
        }catch(Exception e) {
            e.printStackTrace();
            throw new ZxjyException(20002,"批量导入课程分类失败");
        }
    }

    @Override
    public R importSubject(MultipartFile file) {
        List<String> msgs= new ArrayList<>();
        try {

            InputStream inputStream = file.getInputStream();
            Workbook workbook = new HSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);

            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);// 获取每一行数据
                if (row == null) {
                    String msg = i + "行数据为空";
                    msgs.add(msg);
                    continue;
                }
                Cell cell = row.getCell(0);// 获取第一列
                if (cell == null) {
                    String msg = i + "行数据为空0列为空";
                    msgs.add(msg);
                    continue;
                }
                Cell cell2 = row.getCell(1);// 获取第一列
                if (cell == null) {
                    String msg = i + "行数据为空0列为空";
                    continue;
                }

                Subject subject =getByTitle(cell.getStringCellValue());
                // 如果没有  新的一级分类
                if(subject==null) {
                    subject = new Subject();
                    subject.setParentId(0L);// 一级分类
                    subject.setSort(1);
                    subject.setTitle(cell.getStringCellValue());
                    // 新增一级分类
                    subjectMapper.insert(subject);
                }

                //新增2级分类
                Subject subject2= new Subject();
                subject2.setTitle(cell2.getStringCellValue());
                subject2.setParentId(subject.getId());
                subject2.setSort(1);
                if(getByTitle(cell2.getStringCellValue())==null) {// 二级分类不存在 就添加
                    subjectMapper.insert(subject2);
                }
            }

            return  R.ok().data("msg",msgs).message("添加成功");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error().message("添加失败");
    }

    @Override
    public Subject getByTitle(String title) {
        QueryWrapper<Subject> wrapper= new QueryWrapper<>();
        wrapper.eq("title",title);

        return subjectMapper.selectOne(wrapper);
    }

    @Override
    public List<Subject> getAllSubject(Object o) {
        Map<String,Object> params= new HashMap<>();
        params.put("parent_id",0);
        // 获取所有一级分类
        List<Subject> subjectLevel1 = subjectMapper.selectByMap(params);
        for (int i = 0; i <subjectLevel1.size() ; i++) {
            Subject subject1= subjectLevel1.get(i);
            params.put("parent_id",subject1.getId());
            subject1.setLevel2(subjectMapper.selectByMap(params));
        }
        return subjectLevel1;
    }

    @Override
    @Transactional
    public boolean deleteById(Long id) {
        // 先确定是否是 一级分类 并且一级分类下面是否有东西
       QueryWrapper<Subject> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        Integer count = subjectMapper.selectCount(queryWrapper);
        if(count==0){
            int i = subjectMapper.deleteById(id);//删除  真的删除
            if(i>0){
                return  true;
            }
        }
        return false;// 删除失败
    }

    @Override
    @Transactional
    public boolean addSubject(Subject subject) {
       if(null==getByTitle(subject.getTitle())){
           subject.setSort(1);
         return baseMapper.insert(subject) > 0;
       }
        return false;
    }


}
